<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<link href="../../../static/css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../../../static/js/jquery.js"></script>
<script type="text/javascript" src="../../../static/js/getBrandAndProduct.js"></script>
<script type="text/javascript">

    window.datas = {
        brandTypeProductInfo: [],
    }
    window.details = 0;
    //获取品牌商品信息
    function getBrandInfo() {
        $.ajax({
            url: "/queryBrandTypeProductFirmInfo",
            type: "get",
            dataType: "json",
            success: (data) => {
                window.datas.brandTypeProductInfo = data.data;
                //初始化采购单详情
                addCDetail();
            }
        })
    }
    //新增采购物品
    function addCDetail() {
        var detailsNum = window.details + 1;
        window.details = detailsNum;
        let str = '<tr>\n' +
             '         <td><input type="checkbox" class="danXuan"></td>'+
            '          <td class="pal_XuHao">'+detailsNum+'</td>\n' +
            '          <td>\n' +
            '          \t<select class="brandId" id="pad_brand" onchange="brandChange(this)">\n' +
            '            \t<option value="">请选择</option>\n' +
            '            </select>\n' +
            '          </td>\n' +
            '          <td>\n' +
            '          \t<select class="typeId" id="pad_type" onchange="typeChange(this)">\n' +
            '            \t<option value="">请选择</option>\n' +
            '            </select>\n' +
            '          </td>\n' +
            '          <td>\n' +
            '          \t<select class="productId" id="pad_product" onchange="productChange(this)">\n' +
            '            \t<option value="">请选择</option>\n' +
            '            </select>\n' +
            '          </td>\n' +
            '          <td>\n' +
            '          \t<select class="firmId" id="pad_firm">\n' +
            '            \t<option value="">请选择</option>\n' +
            '            </select>\n' +
            '          </td>\n' +
            '          <td><input id="pad_number" class="purchaseNum" type="number" onblur="caculateDetailTotal(this)"/></td>\n' +
            '          <td id="pad_Unit" class="productUnit"> </td>\n' +
            '          <td><input id="pad_univalence" class="productPrice" disabled type="text" /></td>\n' +
            '          <td><input id="pad_money" type="text" class="purchaseDetailTotal" /></td>\n' +
            '        </tr>';
        if (detailsNum > 1 ){
            $("#pad_tbody").append(str);
        }else {
            $("#pad_tbody").html(str);
        }
        datas.brandTypeProductInfo.forEach((item,index)=>{
            $(".brandId").last().append(`
               <option value="${item.brandId}">${item.brandName}</option>`)
        })
    }
    //选择品牌后
    function brandChange(target){
        let brandTypeProductInfo=datas.brandTypeProductInfo;
        let type=[];
        let id=$(target).find("option:selected").val();
        for (let i = 0;i< brandTypeProductInfo.length; i++) {
            if(brandTypeProductInfo[i].brandId==id){
                type=brandTypeProductInfo[i].types;
                break;
            }
        }
        datas.types=type;
        $(target).parents("tr").find(".typeId").html('<option value="">请选择</option>')
        type.forEach((item,index)=>{
            $(target).parents("tr").find(".typeId").append(`<option value="${item.typeId}">${item.typeName}</option>`);
        })
    }
    //选择类型后
    function typeChange(target){
        let types=datas.types;
        let product=[];
        let id=$(target).find("option:selected").val();
        for (let i = 0;i< types.length; i++) {
            if(types[i].typeId==id){
                product=types[i].products;
                break;
            }

        }
        datas.products=product;
        $(target).parents("tr").find(".productId").html('<option value="">请选择</option>')
        product.forEach((item,index)=>{
            if (index ==0){
                $(target).parents("tr").find(".productId").html(`<option value="">请选择</option>`);
                $(target).parents("tr").find(".firmId").html(`<option value="}">请选择</option>`);
            }
            $(target).parents("tr").find(".productId").append(`<option value="${item.productId}">${item.productModel}</option>`);
            $(target).parents("tr").find(".firmId").append(`<option value="${item.firmId}">${item.firmName}</option>`);

        })
    }
    //选择产品型号后
    function productChange(target){
        let products=datas.products;
        let product={};
        let id=$(target).find("option:selected").val();
        for (let i = 0;i< products.length; i++) {
            if(products[i].productId==id){
                product=products[i];
                break;
            }
        }
        $(target).parents("tr").find(".productUnit").text(product.productUnit);
        $(target).parents("tr").find(".productPrice").val(product.productPrice);
        caculateDetailTotal(target);
    }
    //删除订单详情
    function deleteDetail(){
        let details=$("#pad_tbody").children("tr");
        if(details.length<=1){
            alert("最少存在一个详情信息")
        }else{
            checkDanXuan();
        }
        flushDetails();
    }
    //检查复选框并删除
    function checkDanXuan() {
        var items = $(".danXuan")
        for (let i = (items.length-1); i >= 0; i--) {
            var isCheck = items[i].checked;
            if (isCheck){
                $(items[i]).parents("tr").remove();
                window.details--;
            }
        }
    }
    //刷新订单详细
    function flushDetails() {
        window.details = 1;
        var palXuHao = $(".pal_XuHao");
        for (let i = 0; i < palXuHao.length; i++) {
            $(palXuHao[i]).html(window.details);
            window.details++;
        }
        window.details--;
    }
    //计算单个详情总价
    function caculateDetailTotal(target){
        let tr=$(target).parents("tr");
        let price=tr.find(".productPrice").val();
        let num=tr.find(".purchaseNum").val();
        if(num<=0){
            tr.find(".purchaseNum").val(1);
            num=1
        }
        tr.find(".purchaseDetailTotal").val(price*num);
        //计算单个后计总
        caculatePurchaseTotal()
    }
    //计算整个订单总额
    function caculatePurchaseTotal(){
        let count=0;
        $(".purchaseDetailTotal").each((index,item)=>{
            count+=parseInt($(item).val());
        })
        if (count>0){
            $("#pad_TotalMoney").val(count);
        }
    }
    //校验填写信息
    function checkOrderInfo(){
        $(".orderDetailTotal").each((index,item)=>{
            if($(item).val()<=0){
                alert("采购单详情未填写");
                return false;
            }
        })
        // if($(".customName").val()==''){
        //     alert("请输入客户名字");
        //     return false
        // }
        return true;
    }
    let user = JSON.parse(localStorage.getItem("user"));
    var cpaConn = {
        purchaseId: null,
        purchaseTime:null,
        creatId:null,
        checkStatus:null,
        totalMoney:null,
        purchaseDatails: []
    }

    function getParamPAD(){
        caculatePurchaseTotal();
        cpaConn = {
            purchaseId: $("#pad_Id").val(),
            purchaseTime:$("#pad_Time").val(),
            creatId:user.uid,
            checkStatus:$("#pad_Status").val(),
            totalMoney:$("#pad_TotalMoney").val(),
            purchaseDatails:[]
        }
        $("#pad_tbody").children("tr").each((index,item)=>{
            cpaConn.purchaseDatails.push({
                purchaseId:cpaConn.purchaseId,
                count:$(item).find(".purchaseNum").val(),
                productId:$(item).find(".productId option:selected").val(),
                purchasePrice:$(item).find(".productPrice").val(),
                totalMoney:$(item).find(".purchaseDetailTotal").val()
            })
        })
    }
    //生成随机四位数
    function randFour() {
        let str ="";
        for (let i = 0; i < 4; i++) {
            var number = Math.floor(Math.random()*9);
            str+= number;
        }
        return str;
    }
    $(function () {
        getBrandInfo();
        var time = new Date();
        var string = time.toLocaleString();
        var strings = string.split("");
        var timeStr = "";
        for (let i = 0;i<strings.length;i++){
            if (timeStr.length===8){break}
            if (strings[i]!=="/" && strings[i]!==" " && strings[i] !== ":"){
                timeStr += strings[i];
            }
        }
        $("#pad_Id").val("CG"+timeStr+randFour());
        $("#pad_Time").val(string);
        $("#pad_CreatName").val(user.uname);
        caculatePurchaseTotal();
        $("#pad_number").blur(function () {
            let regex = /^[1-9]+[0-9]*/
            var number = $("#pad_number").val();
            if (number.text(regex)){
                alert("请输出正整数");
            }
        })
    })

    function addOnePurchase() {
        getParamPAD();
        var isTrue = confirm("是否保存");
        if (isTrue){
            $.ajax({
                url: "/purchase/addOnePurchase",
                method:"post",
                contentType:"application/json;charset=utf8",
                data:JSON.stringify(cpaConn),
                dataType:"JSON",
                success:function (rel) {
                    if (rel.data){
                        window.location.href = "../lists"
                    }
                }
            })
        }
    }

</script>
</head>

<body>
<div class="place"> <span>位置：</span>
  <ul class="placeul">
    <li>采购管理</li>
    <li>采购单管理</li>
    <li>添加</li>
  </ul>
</div>
<div class="formbody">
  <div class="formtitle"><span>采购单信息</span></div>
  <ul class="forminfo">
    <li>
      <label>采购单编号</label>
      <input id="pad_Id" type="text" value="CG201711180001" readonly="readonly" class="roinput" />
      <i>自动生成不能编辑</i>
    </li>
    <li>
      <label>采购时间</label>
      <input id="pad_Time" type="text" value="2017-11-18 15:36:10" readonly="readonly" class="roinput" />
      <i>不能编辑</i>
    </li>
    <li>
      <label>创建人</label>
      <input id="pad_CreatName" type="text" value="马云" readonly="readonly" class="roinput" />
      <i>不能编辑</i>
    </li>
    <li>
      <label>审核状态</label>
      <input type="text" value="未审核" readonly="readonly" class="roinput" />
      <input id="pad_Status" type="hidden" value="1" />
      <i>初始状态，不能编辑</i>
    </li>
    <li>
      <label>总金额</label>
      <input id="pad_TotalMoney" type="text" readonly="readonly" class="roinput" />
       <i>自动运算，不能编辑</i>
    </li>
    <li>
      <input type="button" value="新增" class="smallbtn" onclick="addCDetail()"/>
      &nbsp;&nbsp;&nbsp;&nbsp;
      <input type="button" value="删除" class="smallbtn" onclick="deleteDetail()"/>
       &nbsp;&nbsp;&nbsp;&nbsp;
      <input type="button" value="保存" class="smallbtn" onclick="addOnePurchase()" />
       &nbsp;&nbsp;&nbsp;&nbsp;
      <input type="button" value="返回" class="smallbtn" onclick="window.location.href='../lists'"/>
    </li>
  </ul>
  <table class="tablelist">
      <thead>
        <tr>
          <th>   </th>
          <th>序号</th>
          <th>品牌</th>
          <th>类型</th>
          <th>型号</th>
          <th>厂商</th>
          <th>数量</th>
          <th>单位</th>
          <th>单价</th>
          <th>金额</th>
        </tr>
      </thead>
      <tbody id="pad_tbody">
      	<tr>
          <td><input type="checkbox" class="danXuan"></td>
          <td class="pal_XuHao">1</td>
          <td>
          	<select id="pad_brand" class="brandId">
            	<option value="">请选择</option>
<!--                <option>联想</option>-->
<!--                <option>海尔</option>-->
<!--                <option>小米</option>-->
            </select>
          </td>
          <td>
          	<select id="pad_type" class="typeId">
            	<option value="">请选择</option>
<!--                <option>笔记本电脑</option>-->
<!--                <option>台式电脑</option>-->
<!--                <option>手机</option>-->
            </select>
          </td>
          <td>
          	<select id="pad_product" class="productId">
            	<option value="">请选择</option>
<!--                <option>X260</option>-->
<!--                <option>E470</option>-->
<!--                <option>T470</option>-->
            </select>
          </td>
          <td>
          	<select id="pad_firm" class="firmId">
            	<option value="">请选择</option>
<!--                <option>北京联想科技股份有限公司</option>-->
<!--                <option>北京京东商贸股份有限公司</option>-->
            </select>
          </td>
          <td><input id="pad_number" class="purchaseNum" type="text" /></td>
          <td id="pad_Unit" class="productUnit">台</td>
          <td><input id="pad_univalence" class="productPrice" disabled type="text" /></td>
          <td><input id="pad_money" class="purchaseDetailTotal" type="text" /></td>
        </tr>
      </tbody>
  </table>
</div>
<script type="text/javascript">
	$('.tablelist tbody tr:odd').addClass('odd');
</script>
</body>
</html>
